package com.yisu.expressway.onedollar.adapter;

import java.util.ArrayList;
import java.util.List;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.yisu.expressway.R;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

public class PicGridListAdapter extends BaseAdapter implements View.OnClickListener {

	public static final int MAX_LIST_SIZE = 9;
	private Context mContext;
	private List<String> mDataList = new ArrayList<>();
	private PicItemClickListener mPicItemClickListener;

	public PicGridListAdapter(Context context, List<String> data,
	                          PicItemClickListener picItemClickListener) {
		mContext = context;
		if (data == null || data.size() > MAX_LIST_SIZE){
			throw new IllegalArgumentException();
		}
		mDataList = data;
		mPicItemClickListener = picItemClickListener;
	}

	@Override
	public int getCount() {
		return mDataList == null ? 0 : mDataList.size();
	}

	@Override
	public String getItem(int position) {
		return mDataList == null ? null : mDataList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null) {
			holder = new ViewHolder();
			LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context
				.LAYOUT_INFLATER_SERVICE);
			convertView = layoutInflater.inflate(R.layout.grid_item_pic, null);
			holder.imgView = (ImageView) convertView.findViewById(R.id.iv_pic);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		holder.imgView.setTag(R.id.iv_pic, position);
		holder.imgView.setOnClickListener(this);

		holder.imgView.setScaleType(ImageView.ScaleType.CENTER_CROP);
		String goodspic = getItem(position);
		if (!TextUtils.isEmpty(goodspic)) {
				Glide.with(mContext).load(goodspic).asBitmap()
					.placeholder(R.drawable.avatar_default).diskCacheStrategy(DiskCacheStrategy.ALL)
					.centerCrop().animate(R.anim.fade_in_image).into(holder.imgView);
		}
		return convertView;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.iv_pic:
				int position = (Integer) v.getTag(v.getId());
				if (mPicItemClickListener != null) {
					mPicItemClickListener.onPicItemClick(mDataList.get(position));
				}
				break;
			default:
				break;
		}
	}

	public interface PicItemClickListener {
		void onPicItemClick(String picUrl);
	}

	public class ViewHolder {
		public ImageView imgView;
	}
}
